Imports System
Imports System.Collections.Generic

Namespace ASPNET.StarterKit.BusinessLogicLayer

    Public Class ProjectComparer
        Implements IComparer(Of Project)

        Private _sortColumn As String
        Private _reverse As Boolean

        Public Sub New(ByVal sortExpression As String)

            If (Not String.IsNullOrEmpty(sortExpression)) Then
                Me._reverse = sortExpression.ToLowerInvariant().EndsWith(" desc")
                If _reverse Then
                    Me._sortColumn = sortExpression.Substring(0, sortExpression.Length - 5)
                Else
                    Me._sortColumn = sortExpression
                End If
            End If

        End Sub

        Public Function Compare(ByVal x As Project, ByVal y As Project) As Integer Implements IComparer(Of Project).Compare

            Dim retVal As Integer = 0

            Select Case Me._sortColumn

                Case "CompletionDate"
                    retVal = DateTime.Compare(x.CompletionDate, y.CompletionDate)

                Case "Description"
                    retVal = String.Compare(x.Description, y.Description, StringComparison.InvariantCultureIgnoreCase)

                Case "EstimateDuration"
                    retVal = CInt(x.EstimateDuration - y.EstimateDuration)

                Case "Id"
                    retVal = (x.Id - y.Id)

                Case "ManagerUserName"
                    retVal = String.Compare(x.ManagerUserName, y.ManagerUserName, StringComparison.InvariantCultureIgnoreCase)

                Case "Name"
                    retVal = String.Compare(x.Name, y.Name, StringComparison.InvariantCultureIgnoreCase)

            End Select

            If Me._reverse Then
                Return -retVal
            Else
                Return retVal
            End If

        End Function

    End Class
  
End Namespace

